import {Component, OnInit} from '@angular/core';
import {FormControl, FormGroup, Validators} from "@angular/forms";
import {NzMessageService} from "ng-zorro-antd/message";
import {BarnMenuService} from "../service/barn-menu.service";
import {ActivatedRoute} from "@angular/router";

@Component({
  selector: 'app-menu-edit',
  templateUrl: './menu-edit.component.html',
  styleUrls: ['./menu-edit.component.less']
})
export class MenuEditComponent implements OnInit {

  loading = false;
  remarkMaxLength = 1000
  pathErrorTip = "PATH最大1000字符"
  parentId: string
  parentName: string
  iconBase64: string | ArrayBuffer
  reader = new FileReader();

  validateForm: FormGroup

  constructor(private msg: NzMessageService, private menuService: BarnMenuService, private routeInfo: ActivatedRoute) {
  }

  ngOnInit(): void {
    this.reader.addEventListener("load", () => {
      this.iconBase64 = this.reader.result
    })
    const pid = this.routeInfo.snapshot.queryParams["pid"];
    this.parentId = this.routeInfo.snapshot.queryParams["parentId"];
    this.parentName = this.routeInfo.snapshot.queryParams["parentName"];
    if (pid) {
      this.loading = true
      this.menuService.getById(pid).subscribe(value => {
        if (value) {
          this.validateForm.patchValue(value);
          this.iconBase64 = value.icon
          this.parentId = value.parentId
          this.parentName = value.parentName
        }
      }, () => this.loading = false, () => this.loading = false)
    }

    const pathValidator = [Validators.maxLength(1000)];
    if (this.parentId) {
      pathValidator.push(Validators.required)
      this.pathErrorTip = "PATH最大1000字符且不能为空"
    }

    this.validateForm = new FormGroup({
      menuName: new FormControl(null, [Validators.required, Validators.maxLength(20)]),
      pid: new FormControl(null),
      remark: new FormControl(null, [Validators.maxLength(this.remarkMaxLength)]),
      path: new FormControl(null, pathValidator),
    });
  }

  submitForm() {
    if (this.validateForm.valid) {
      const data = this.validateForm.getRawValue();
      data.icon = this.iconBase64
      data.parentId = this.parentId
      this.loading = true
      this.menuService.save(data)
        .subscribe(value => {
          this.validateForm.patchValue(value);
          this.loading = false
          this.msg.success("保存成功")
        }, () => this.loading = false)
    } else {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    }

  }

  beforeUpload = (file: File) => {
    if (file.size > 61440) {
      this.msg.error("文件最多 60kb")
      return false
    }

    if (!file.name.endsWith(".png")) {
      this.msg.error("只支持 .png图片")
      return false
    }
    this.reader.readAsDataURL(file);
    return false
  }

  get pid() {
    return this.validateForm.get("pid").value
  }

}
